﻿
#include <log4lite/platform_config.h>
#include <log4lite/layout.h>
#include <log4lite/log_time.h>
#include <log4lite/log_item.h>

#include <iostream>
#include <iomanip>

#if defined(LOG4_WINDOWS)
#	include <tchar.h>
#	include <WinSock2.h>
#	pragma comment(lib, "Ws2_32")
#elif defined(LOG4_LINUX)
#	include "liggen.h"
#endif

namespace log4lite {
	
	helpers::LogTime SongLayout_time_base;
	void initializeLayout ()
	{
		SongLayout_time_base = helpers::LogTime::gettimeofday();
#if defined(LOG4_WINDOWS)
		static WSADATA wsa;
		WSAStartup(MAKEWORD(2, 2), &wsa);
#endif
	}

	void SyslogLayout::formatAndAppend(tostream& output, const LogItem& item)
	{
		const tstring time = item.getTimestamp().toSting(T_TEXT("%b %d %X "));
		output << time
			<< _hostName
			<< T_TEXT(" ")
			<< _lcm.toString(item.getCatagory()) 
			<< T_TEXT(" : ")
			<< item.getMessage()
			<< T_TEXT("\n");
	}

	SyslogLayout::SyslogLayout()
	{
#if defined(LOG4_WINDOWS)
		if (gethostname(_hostName, sizeof(_hostName)) < 0) { 
			_hostName[0] = ' ';
			_hostName[1] = 0;
		}
#endif
	}

	void SongLayout::formatAndAppend(tostream& output, const LogItem& item)
	{
#if defined(LOG4_WINDOWS)
		_tsplitpath(item.getFilename().c_str(), NULL, NULL, _fname, _ext);
		output << _fname << _ext;
#elif defined(LOG4_LINUX)
		char fname = basename(item.getFilename().c_str());
		output << fname;
#endif
		output<< T_TEXT(" ")
			<< item.getLineNo()
			<< T_TEXT(" : ")
			<< item.getMessage() 
			<< T_TEXT("\n");
	}

	void SimpleLayout::formatAndAppend(tostream& output, const LogItem& item)
	{
		output << _lcm.toString(item.getCatagory()) 
			<< T_TEXT(" - ")
			<< item.getMessage() 
			<< T_TEXT("\n");
	}
}
